package com.qf.j2112.controller;

import com.qf.j2112.po.SysUser;
import com.qf.j2112.utils.JwtUtil;
import com.qf.j2112.vo.AjaxResult;
import com.qf.j2112.vo.logInvo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.qf.j2112.service.SysUserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户Controller
 * @author j2112
 * @date 2022-04-12
 */

@CrossOrigin
@Slf4j
@RestController
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    RedisTemplate redisTemplate;

    /*查询用户列表*/
    @RequestMapping(value = "/userlist",method = RequestMethod.GET)
    public AjaxResult listuser() {
        List<SysUser> list = sysUserService.selectSysUserList();
        return AjaxResult.success("查询成功",list);
    }


    /* 获取用户详细信息*/
    @GetMapping(value = "/user/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Integer userId)
    {
        return AjaxResult.success(sysUserService.selectSysUserByUserId(userId));
    }

    /* 新增用户*/
    @RequestMapping(value = "/user/add",method = RequestMethod.POST)
    public AjaxResult add(@RequestBody SysUser sysUser) {
        return AjaxResult.success("添加成功",sysUserService.insertSysUser(sysUser));
    }

    /*修改用户*/
    @RequestMapping(value = "/userupdate",method = RequestMethod.PUT)
    public AjaxResult edit(@RequestBody SysUser sysUser) {
        return AjaxResult.success("修改成功",sysUserService.updateSysUser(sysUser));
    }

    //用户登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public AjaxResult login(@RequestBody logInvo logInvo){
        log.info("登录信息为："+logInvo);
        SysUser sysUser=sysUserService.findUserByUname(logInvo.getUserName());
        if (!ObjectUtils.isEmpty(sysUser)&&sysUser.getUserPassword().equals(logInvo.getPassword())){
            String token= JwtUtil.getToken(String.valueOf(sysUser.getUserId()));
            log.info("token是"+token);
            logInvo.setToken(token);
            return AjaxResult.success("登录成功",logInvo);
        }else {
            log.info("用户名或密码错误");
            return AjaxResult.error("用户名或密码错误,登录失败");
        }
    }

}
